package processevent

import (
	"github.com/golang/glog"
	"strings"
	"sync"
	"fmt"
	"cloud_worm/worm/config"
	"io/ioutil"
	"errors"
	"cloud_worm/util/proto/ujson"
	"cloud_worm/util/ufile"
)

type KeyList struct {
	List 		[]string
	sync.Mutex
}

type WhiteList struct {
	SelfList 	KeyList
	ParentList 	KeyList
}

var WhiteListInstance = &WhiteList{}

func (w *WhiteList) LoadWhiteList() error {
	destFile := "./var/" + ujson.CmdRuleFile
	fileURL := fmt.Sprintf("%s/worm/worm/%s",
		config.CfgInst.StartConfig.(*config.ClientConfig).ServerSet.AutoConfigURL, ujson.CmdRuleFile)

	if err := ufile.DownloadFile(fileURL, destFile); err != nil {
		glog.Error(fmt.Sprintf("download file'%s' error: %s", ujson.CmdRuleFile, err.Error()))
		glog.Error(fmt.Sprintf("download url: %s", fileURL))
		return err
	}

	data, err := ioutil.ReadFile(destFile)
	if err != nil {
		return err
	}
	if strings.Contains(string(data), ujson.Page404NotFound) {
		return errors.New(fmt.Sprintf("url: %s, 404 page not found", fileURL))
	}

	tmp := strings.Split(string(data), "\n")

	self := make([]string, 0, len(tmp))
	parent := make([]string, 0, len(tmp))
	for _, item := range tmp {
		l := strings.TrimSpace(item)
		if l == "" {
			continue
		}
		ln := strings.Split(l, "|")
		if len(ln) != 2 {
			continue
		}

		// 1--parent; 2--self
		if strings.TrimSpace(ln[0]) == "1" {
			parent = append(parent, strings.TrimSpace(ln[1]))
		} else if strings.TrimSpace(ln[0]) == "2" {
			self = append(self, strings.TrimSpace(ln[1]))
		} else {
			continue
		}
	}

	WhiteListInstance.ParentList.Lock()
	WhiteListInstance.ParentList.List = parent
	glog.Infof("parent list: %v", WhiteListInstance.ParentList.List)
	WhiteListInstance.ParentList.Unlock()

	WhiteListInstance.SelfList.Lock()
	WhiteListInstance.SelfList.List = self
	glog.Infof("self list: %v", WhiteListInstance.SelfList.List)
	WhiteListInstance.SelfList.Unlock()

	return nil
}

// 父进程
var defaultParentList = []string {
	"TsysAgent",
	"TsysProxy",
	"safe_TsysAgent.sh",		// safe_TsysAgent.sh
	"sentry",					// sentry-agent
	"wukong",					// wukong
	"LogAgent",					// ./LogAgent
	"/usr/bin/kdumpctl",
	"/home/mapp/dylan_github",	// dylan_github
	"docker-containerd", 		// docker
	"docker-runc",
	"/usr/bin/kubelet",
	"/usr/bin/tsar",
	"/usr/sbin/ntpdate",
	"0yum-daily.cron",			// cron
	"0yum-hourly.cron",

	"/usr/bin/logger",
	"/usr/sbin/hwclock",
	"/usr/bin/basename",
	"/usr/bin/gawk",

	"neutron",
	"/bin/ovs-vsctl",
	"loadavg",
	"/usr/sbin/sendmail",
}

// 子进程
var defaultSelfList = []string {
	"LogAgent",
	"systemd-cgroups-agent",
	"logagent",
	"/usr/sbin/sendmail",
	"/sbin/modprobe",
}
